package DAO;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.ArrayList;

public class DatabaseDAO implements DAOInterface{
	
	private static DatabaseDAO instance = null;
	
	public DatabaseDAO(){
	}
	
	public static DatabaseDAO getInstance(){
		if(instance == null)
			instance = new DatabaseDAO();
		
		return instance;
	}

	@Override
	public boolean save(String item, String path) {
		try {
			RandomAccessFile afile=new RandomAccessFile(path, "rw");
			boolean written = false;
			while(!written){
				try{
					FileLock lock = afile.getChannel().lock();

					try{
						afile.seek(afile.length());
						afile.writeBytes(item+"\r\n");
						afile.setLength(afile.length());
						written=true;
					} finally {
						lock.release();
						afile.close();
					}
				} catch (OverlappingFileLockException ofle) {
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return false;
	}
	@Override
	public boolean update(String item) {
		return false;
	}
	@Override
	public boolean find(String item) {
		return false;
	}
	@Override
	public ArrayList<String> findAll() {
		return null;
	}
	@Override
	public void delete(String item, String path) {
		try {
			RandomAccessFile afile = new RandomAccessFile(path, "rw");
			RandomAccessFile afile2 = new RandomAccessFile(new File(path.substring(0, path.length()-4)+"2.txt"), "rw");
			
			boolean written = false;
			while(!written){
				try{
					FileLock lock = afile.getChannel().lock();
					
					try{
						String next = null;  
			            while ((next = afile.readLine()) != null) {  
			            	if(!next.equals(item)){
			            		afile2.writeBytes(next+"\r\n");
			            	}
			            }
			            afile2.setLength(afile2.length());
						afile2.close();

						written=true;
					} finally {
						lock.release();
						afile.close();
						
						File f = new File(path);
						f.delete();
						
						File f2 = new File(path.substring(0, path.length()-4)+"2.txt");
						f2.renameTo(new File(path));
					}
				} catch ( OverlappingFileLockException ofle ) {
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
